package tiger.android_hierarchy_view;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class DataUtil {

	public static ArrayList<BrokerOrgEntity>  makeTestDatas(ArrayList<BrokerOrgEntity> followUpList){
        if(followUpList==null){
			followUpList = new ArrayList<>();
		}
		return followUpList;
	}

	public static void makeDatas(JSONObject jsonobject, int id) {
		System.out.println("#jsonObject:" + jsonobject.toJSONString());
		ArrayList<BrokerOrgEntity> followUpList = new ArrayList<BrokerOrgEntity>();
		JSONObject resultObj = jsonobject.getJSONObject("result");
		if (resultObj.getIntValue("code") == 0) {
			JSONObject dataObj = jsonobject.getJSONObject("data");
			JSONArray array = dataObj.getJSONArray("list");
			parseOrgList(array, followUpList, 0);
		}
	}

	public static  void parseOrgList(JSONArray array,
			ArrayList<BrokerOrgEntity> followUpList, int level) {
		if (array == null || array.size() <= 0) {
			return;
		}
		int size = array.size();
		JSONObject obj;
		for (int i = 0; i < size; i++) {
			obj = array.getJSONObject(i);
			String departmentId = obj.getString("departmentId");
			String departmentName = obj.getString("departmentName");
			JSONArray employeeListArray = obj.getJSONArray("employeeList");
			int empSize = employeeListArray.size();
			BrokerOrgEntity orgEntity = new BrokerOrgEntity(departmentName,
					departmentId, null);
			orgEntity.setLevel(level);
			JSONObject empObj;
			List<BrokerOrgEntity> childEntitys = new ArrayList<BrokerOrgEntity>();
			for (int j = 0; j < empSize; j++) {
				empObj = employeeListArray.getJSONObject(j);
				parseInfoList(departmentId, departmentName, empObj, orgEntity,
						childEntitys, level + 1);
			}
			orgEntity.setList(childEntitys);
			followUpList.add(orgEntity);
		}
	}

	private static void parseInfoList(String departmentId, String departmentName,
			JSONObject obj, BrokerOrgEntity orgEntity,
			List<BrokerOrgEntity> childEntitys, int level) {
		BrokerOrgEntity childEntity = null;
		if (obj != null) {
			BrokerEntity entity = new BrokerEntity();
			entity.setDepartmentId(departmentId);
			entity.setDepartmentName(departmentName);
			entity.setBrokerName(obj.getString("userName"));
			entity.setBrokerId(obj.getString("userId"));
			childEntity = new BrokerOrgEntity(obj.getString("userName"),
					entity, orgEntity);
			childEntity.setLevel(level);
			childEntitys.add(childEntity);
		}
	}
}
